<?php


namespace app\admin\controller\jizhan;


use app\admin\model\HtnsBasestationStore;
use app\admin\model\HtnsOrder;
use app\admin\model\HtnsOrderCartInfo;
use app\admin\model\HtnsOrderRefund;
use app\admin\model\HtnsOrderStatus;
use app\admin\model\HtnsProduct;
use app\admin\model\HtnsUser;
use app\admin\traits\Curd;
use app\admin\traits\HtnsTrait;
use app\api\services\HtnsApiService;
use app\api\services\HtnsService;
use app\api\services\OrderCartInfoService;
use app\api\services\RefundOrderService;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\Exception;
use think\facade\Cache;

/**
 * Class Admin
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="海淘-售后订单")
 */
class RefundOrder extends AdminController
{

    use Curd;
    use HtnsTrait;

    public $htnsUser;// 海淘-用户模型
    public $htnsOrder;// 海淘-商品模型
    public $htnsOrderCartInfo;// 海淘-订单详情模型


    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new HtnsOrderRefund();
        $this->htnsUser = new HtnsUser();
        $this->htnsOrder = new HtnsOrder();
        $this->htnsOrderCartInfo = new HtnsOrderCartInfo();

        $refundStatus = $this->model->getRefundStatus();
        $this->assign('refundStatus', $refundStatus);
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index($export = 0)
    {
        $storeId = session('admin')['store_id'];//当前用户门店id
        if ($this->request->isAjax() || $export) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 自定义搜索条件解析
            $whereArr = [];
            $filter   = input('filter');
            $filter = htmlspecialchars_decode($filter);// html特殊字符转化&quot;转换为'
            if ($filter) {
                $filterArr = json_decode($filter, true);

                if (isset($filterArr['id'])) {
                    $whereArr[] = ['id', '=', $filterArr['id']];
                }
                if (isset($filterArr['order_id'])) {
                    $whereArr[] = ['order_id', '=', $filterArr['order_id']];
                }
                if (isset($filterArr['add_time'])) {
                    $time       = explode(' - ', $filterArr['add_time']);
                    $whereArr[] = ['add_time', 'between', [strtotime($time[0]), strtotime($time[1])]];
                }
                if (isset($filterArr['old_order_id'])) {
                    $whereo['order_id'] = $filterArr['old_order_id'];
                    $order = HtnsOrder::where($whereo)->find();
                    $whereArr[] = ['store_order_id', '=', $order['id']];
                }
                if (isset($filterArr['refundStatus']) && $filterArr['refundStatus']) {
                    // 根据售后状态查询售后订单
                    if($filterArr['refundStatus'] > -1){
                        $whereArr[] = ['refund_type', '=', $filterArr['refundStatus']];
                    }else{
                        $whereArr[] = ['refund_type', '=', 0];
                    }
                }
            }
            if($storeId){
                $whereo['store_id'] = $storeId;
                $whereo['paid'] = 1;
                $order = HtnsOrder::where($whereo)->select()->toArray();
                if($order){
                    $orderIdArr = array_column($order,'id');
                    $whereArr[] = ['store_order_id', 'in', $orderIdArr];
                }
            }
            $whereArr[] = ['is_cancel', '=', 0];
            $whereArr[] = ['is_del', '=', 0];
            $whereArr[] = ['is_system_del', '=', 0];
            $whereArr[] = ['is_pink_cancel', '=', 0];

            $cacheWhereKey = 'refundOrder';
            if($export){
                $page = 1;
                $limit = 10000;
                $cacheWhere = Cache::get($cacheWhereKey);
                if(!empty($cacheWhere)){
                    $whereArr = $cacheWhere;
                }
            }else{
                if(!empty($whereArr)){
                    $resc = Cache::set($cacheWhereKey , $whereArr , 3600 * 24);
                }
            }
            $count = $this->model
                ->where($whereArr)
                ->count();
            $list  = $this->model
                ->where($whereArr)
                ->page($page, $limit)
                ->order($this->sort)
//                ->fetchSql(true)
                ->select()
                ->toArray();

            $htnsOrderRefund = new HtnsOrderRefund();
            $ret = [];
            foreach ($list as &$v) {
                $v['add_time'] = $v['add_time'] ? date('Y-m-d H:i:s',$v['add_time']) : '';
                $imgArr = json_decode($v['refund_img'] , true);
                if($imgArr){
                    $imgStr = '';
                    foreach ($imgArr as $vi) {
                        $imgStr = '<br/><img src="'.$vi.'" height="20%" width="20%" data-image="测试图片放大">';
                    }
                    $v['refund_reason'] .= $imgStr;
                }

                $user = HtnsUser::find($v['uid']);
                $v['userInfo'] = $user['real_name'].'-'.$user['phone'];

                $order = HtnsOrder::find($v['store_order_id']);
                $v['old_order_id'] = $order['order_id'];
                $v['payPrice'] = $order['pay_price'];

                $cartInfo = json_decode($v['cart_info'] , true);
                $str               = '';
                $v['price'] = 0;
                foreach ($cartInfo as $vc) {
                    $productInfo   = $vc['productInfo'];
                    $attrInfo      = $vc['attrInfo'];
                    $str           .= sprintf('%s|%s|%s|<br/>', $productInfo['store_name'], $attrInfo['suk'],
                        $vc['truePrice'] . 'x' . $vc['cart_num']);
                    $v['price'] += $vc['sum_price'];
                }
                $v['productInfo']     = $str;

                $refundStatus = $htnsOrderRefund->getOrderRefundStatus(0,$v['id']);
                $v['refundStatus'] = $refundStatus;
            }
//            halt($list);
            // 导出
            if($export){
                return $list;
            }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $row['waitRefund'] = $this->model->getWaitRefund();
        $row['refundSuc'] = $this->model->getRefundSucNum();
        $row['refuseRefund'] = $this->model->getRefuseRefundNum();
        $row['refundFail'] = $this->model->getRefundFailNum();
        $this->assign('row',$row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {

//        list($page, $limit, $where) = $this->buildTableParames();
//        $tableName = 'mall_cate';
////        $tableName = CommonTool::humpToLine(lcfirst($tableName));
//        $prefix = config('database.connections.mysql.prefix');
//        $dbList = \think\facade\Db::query("show full columns from {$prefix}{$tableName}");
//        $header = [];
//        foreach ($dbList as $vo) {
//            $comment = !empty($vo['Comment']) ? $vo['Comment'] : $vo['Field'];
//            if (!in_array($vo['Field'], $this->noExportFields)) {
//                $header[] = [$comment, $vo['Field']];
//            }
//        }


        $header = [
            ['售后订单ID','id'],
            ['订单号','order_id'],
            ['原始订单号','old_order_id'],
            ['用户信息','userInfo'],
            ['商品信息','productInfo'],
            ['实际支付','payPrice'],
            ['发起退款时间','add_time'],
            ['退款状态','refundStatus'],
            ['退款信息','refund_reason'],
            ['售后备注','remark'],
        ];
        $list = $this->index(1);
        $fileName = time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="订单详情")
     */
    public function detail($id)
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        $row = $row->toArray();
        $row['add_time'] = $row['add_time'] ? date('Y-m-d H:i:s',$row['add_time']) : '';

        $htnsOrderRefund = new HtnsOrderRefund();
        $refundStatus = $htnsOrderRefund->getOrderRefundStatus(0,$id);
        $row['refundStatus'] = $refundStatus;

        $schedule = $htnsOrderRefund->getRefundSchedule($row['refund_type']);
        $row = array_merge($row,$schedule);

        $order = HtnsOrder::find($row['store_order_id']);
        if($order){
            $row['orderId'] = $order['order_id'];
            $row['payPrice'] = $order['pay_price'];
            $row['useIntegral'] = $order['use_integral'];
            $row['couponPrice'] = $order['coupon_price'];
            $row['real_name'] = $order['real_name'];
            $row['user_phone'] = $order['user_phone'];
            $row['user_address'] = $order['user_address'];
            $row['delivery_name'] = $order['delivery_name'];
            $row['delivery_id'] = $order['delivery_id'];
        }
        $row['refundImg'] = [];
        if($row['refund_img']){
            $refundImg = json_decode($row['refund_img'] , true);
            $row['refundImg'] = $refundImg;
        }

//        $htnsService = new HtnsService();
//        $express = $htnsService->getExpress($order['id'],$order['status']);
//        $row['expressStatu'] = '';
//        $row['express'] = [];
//        if($express['code'] && $express['data']){
//            $row['expressStatu'] = $express['data']['expressStatu'];
//            $row['express'] = $express['data']['express'];
//        }

        $htnsApiService = new HtnsApiService();
        $express = $htnsApiService->getExpress($order['id'],$order['status']);
        $row['expressStatu'] = '';
        $row['express'] = [];
        if($express['code'] && $express['data']){
            $row['expressStatu'] = $express['data']['expressStatu'];
            $row['express'] = $express['data']['express'];
        }

        $row['refundExpressStatu'] = '';
        $row['refundExpress'] = [];
        $row['refundDeliveryName'] = '';
        $row['refundDeliveryId'] = '';
        if($row['refund_express']){
            $row['refundDeliveryName'] = $row['refund_express_name'];
            $row['refundDeliveryId'] = $row['refund_express'];
            $row['refundExpressStatu'] = '已发货';
            // 快递查询
            $refundExpress = $htnsApiService->getNationalExpress($row['refund_express']);
            if($refundExpress['code'] && isset($refundExpress['data']['issign'])){
                $row['refundExpressStatu'] = $refundExpress['data']['issign'] ? '已签收' : $row['refundExpressStatu'];
                $row['refundExpress'] = $refundExpress['data']['express'];
            }
        }

        $cartInfo = json_decode($row['cart_info'],true);
        $htnsProduct = new HtnsProduct();
        $row['products'] = [];
        foreach ($cartInfo as $v) {
            $productInfo = $v['productInfo'];
            $attrInfo = $v['attrInfo'];

            $product['store_name'] = $productInfo['store_name'];
            $product['image'] = $attrInfo['image'];
            $product['recommend_image'] = isset($productInfo['recommend_image']) ? $productInfo['recommend_image'] : $product['image'];
            $erp_id = isset($productInfo['erp_id']) ? $productInfo['erp_id'] : 1;
            $product['hcName'] = $htnsProduct->hcName[$erp_id];
            $product['price'] = $attrInfo['price'];
            $product['cart_num'] = $v['cart_num'];
            $product['sumPrice'] = $product['cart_num'] * $product['price'];
            $product['payPrice'] = $order['pay_price'];
            $product['refundPrice'] = $row['refund_price'];
            $product['refundIntegral'] = $order['use_integral'];
            $row['products'][] = $product;
        }
//        halt($row['refundImg']);
        $refundOrderService = new RefundOrderService();
        $refundLog = $refundOrderService->refundLog($id);
        $this->assign('refundLog', $refundLog);
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="退款审批")
     */
    public function refundExamine()
    {
//        halt('refundExamine',input(),$this->request->isPost());
        $id = input('id');
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');

        $order               = HtnsOrder::find($row['store_order_id']);
        $row['old_order_id'] = $order['order_id'];
        $row['status']       = 1;
        if ($row['refund_type'] == 3) {
            $row['status'] = 0;
        }

        if ($this->request->isPost() || input('submit')) {
            $post = input();
            $updateData['remark'] = $post['remark'];
            $where['id'] = $id;
            $this->model->where($where)->update($updateData);

            try {
                // 查询是否已经审核通过,审核过不能重复审核
                // 退货待收货,可以再次审核退款,其它状态只能审核一次
                if ($row['refund_type'] > 3 && $row['refund_type'] != 5) {
                    $this->error('已经审核通过,不能重复审核');
                }
//                $htnsService = new HtnsService();
                $htnsApiService = new HtnsApiService();
                if ($row['refund_type'] >= 1 && $row['refund_type'] <=5) {
                    // 同意退款
                    if ($post['status']) {
                        // 仅退款
                        if($row['refund_type'] == 1 || $row['refund_type'] == 3 || $row['refund_type'] == 5){
                            $res = $htnsApiService->refundAgree($row['id'], $row['order_id'], $post['refund_price']);
                            if ($res['code']) {
                                $this->success('退款成功');// $data = '', $url = null, $wait = 3, array $header = [] , $type = ''
                            } else {
                                $this->error($res['msg']);
                            }
                        }elseif ($row['refund_type'] == 2){
                            // 退货退款
                            $res = $htnsApiService->refundAgreeProduct($row['id']);
                            if ($res['code']) {
                                $this->success('操作成功');
                            } else {
                                $this->error($res['msg']);
                            }
                        }
                    } else {
                        if (empty($post['refuse_reason'])) {
                            $this->error('拒绝退款,拒绝原因必填');
                        }
                        // 不同意退款
                        $res = $htnsApiService->refundNoAgree($row['id'], $row['order_id'], $post['refuse_reason']);
//                        halt($res['msg']);
                        if ($res['code']) {
                            $this->success('操作成功');
                        } else {
                            $this->error($res['msg']);
                        }
                    }
                }
            } catch (Exception $e) {
                halt($e->getMessage());
                $this->error('操作失败-'.$e->getTraceAsString());
            }
        }
        $this->assign('row', $row);
        return $this->fetch();
    }
}